'use strict'

const {Blogs,Op} =require('../model');

let fn_list =async(ctx,next)=>{
    let keyword =ctx.request.query.keyword || '';
    if(keyword){
        let list =await Blogs.findAll({
            where:{
                [Op.or]:[
                    {id:isNaN(keyword) ? 0:parseInt(keyword)},
                    {title:keyword},
                    {digest:keyword},
                    {content:keyword},
                    {classify:keyword},
                    {author:keyword}
                ]
            },
            order:['id']
        })
        ctx.body ={
            code:1000,
            data:list,
            msg:'请求成功'
        }
    }else{
        let list =Blogs.findAll({
            order:['id']
        })
        ctx.body ={
            code:1000,
            data:list,
            msg:'请求成功'
        }
    }
}

let fn_getbyid =async(ctx,next)=>{
    let id =ctx.request.params.id;
    let blog =await Blogs.findByPk(id);
    if(blog){
        ctx.body ={
            code:1000,
            data:blog,
            msg:'请求成功'
        }
    }else{
        ctx.body ={
            code:900,
            data:'',
            msg:'请求失败'
        }
    }
}

let fn_post =async(ctx,next)=>{
    let obj =ctx.request.body;
    await Blogs.create(obj);
    ctx.body =obj;
}

let fn_put =async(ctx,next)=>{
    let id =ctx.request.params.id;
    let obj =ctx.request.body;
    let blog =await Blogs.findByPk(id);
    if(blog){
        Blogs.update(obj,{
            where:{id:id}
        })
        ctx.body ={
            code:1000,
            data:blog,
            msg:'修改成功'
        }
    }else{
        ctx.body ={
            code:900,
            data:'',
            msg:'请求失败'
        }
    }
}

let fn_delete =async(ctx,next)=>{
    let id =ctx.request.params.id;
    let blog =await Blogs.findByPk(id);
    if(blog){
        Blogs.destroy({
            where:{id:id}
        })
        ctx.body ={
            code:1000,
            data:{id},
            msg:'删除成功'
        }
    }else{
        ctx.body ={
            code:900,
            data:'',
            msg:'请求失败'
        }
    }
}


module.exports ={
    'get /blog':fn_list,
    'get /blog/:id':fn_getbyid,
    'post /blog':fn_post,
    'put /blog/:id':fn_put,
    'delete /blog/:id':fn_delete
}

